package com.ml.loan.sys.controller;

import com.ml.loan.common.BaseController;
import com.ml.loan.common.annotaion.OperLog;
import com.ml.loan.common.model.JsonResult;
import com.ml.loan.common.model.PageResult;
import com.ml.loan.common.redis.RedisService;
import com.ml.loan.common.redis.keys.UserKey;
import com.ml.loan.common.shiro.EndecryptUtil;
import com.ml.loan.common.utils.RegExpUtil;
import com.ml.loan.sys.model.Role;
import com.ml.loan.sys.model.User;
import com.ml.loan.sys.service.RoleService;
import com.ml.loan.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户管理
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {
    private static final String DEFAULT_PSW = "123456";  // 用户默认密码
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisService redisService;

    @RequiresPermissions(value = {"user:view", "user:viewByPartyB"}, logical = Logical.OR)
    @RequestMapping
    public String user(Model model) {
        List<Role> roles = roleService.list();
        model.addAttribute("roles", roles);
        return "system/user.html";
    }

    @RequiresPermissions(value = {"user:view", "user:viewByPartyB"}, logical = Logical.OR)
    @RequestMapping("/partyB")
    public String partyB(Model model) {
        List<Role> roles = roleService.list();
        model.addAttribute("roles", roles);
        return "system/userPartyb.html";
    }

    @RequestMapping("/userInfo")
    public String userInfo(Model model) {
        model.addAttribute("loginUser", userService.getByUserId(getLoginUserId()));
        return "system/tpl-userInfo.html";
    }

    @ResponseBody
    @RequestMapping("/checkPwd")
    public JsonResult checkPwd() {
        User user = userService.getByUserId(getLoginUserId());
        if (user != null && EndecryptUtil.encrytMd5(DEFAULT_PSW, 3).equals(user.getPassword())) {
            return JsonResult.ok().put("data", true);
        }
        return JsonResult.ok().put("data", false);
    }

    /**
     * 查询用户列表
     */
    @RequiresPermissions(value = {"user:view", "user:viewByPartyB"}, logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/list")
    @OperLog(module = "SYS", desc = "系统用户列表-查询")
    public PageResult<User> list(Integer page, Integer limit, Integer type, String searchKey, String searchValue) {
        return userService.listUser(page, limit, type, searchKey, searchValue);
    }

    /**
     * 添加用户
     **/
    @RequiresPermissions(value = {"user:update", "user:updateByPartB"}, logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/add")
    @OperLog(module = "SYS", desc = "系统用户列表-新增", result = true)
    public JsonResult add(User user, String roleIds) {
        user.setState(0);
        user.setPassword(EndecryptUtil.encrytMd5(DEFAULT_PSW, 3));
        user.setOperator(getLoginUserName());
        if (userService.add(user, getRoleIds(roleIds))) {
            return JsonResult.ok("添加成功，初始密码为" + DEFAULT_PSW);
        } else {
            return JsonResult.error("添加失败");
        }
    }


    /**
     * 修改用户
     **/
    @RequiresPermissions(value = {"user:update", "user:updateByPartB"}, logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/update")
    @OperLog(module = "SYS", desc = "系统用户列表-更新", result = true)
    public JsonResult update(User user, String roleIds) {
        if (userService.update(user, getRoleIds(roleIds))) {
            return JsonResult.ok("修改成功");
        } else {
            return JsonResult.error("修改失败");
        }
    }

    @ResponseBody
    @RequestMapping("/updateInfo")
    @OperLog(module = "SYS", desc = "系统用户列表-更新", result = true)
    public JsonResult updateInfo(User user) {
        if (userService.updateById(user)) {
            return JsonResult.ok("修改成功");
        } else {
            return JsonResult.error("修改失败");
        }
    }

    // 用逗号分割角色
    private List<Integer> getRoleIds(String rolesStr) {
        List<Integer> roleIds = new ArrayList<>();
        if (rolesStr != null) {
            String[] split = rolesStr.split(",");
            for (String t : split) {
                try {
                    roleIds.add(Integer.parseInt(t));
                } catch (Exception e) {
                }
            }
        }
        return roleIds;
    }

    /**
     * 修改用户状态
     **/
    @RequiresPermissions(value = {"user:update", "user:updateByPartB"}, logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/updateState")
    @OperLog(module = "SYS", desc = "系统用户列表-状态", result = true)
    public JsonResult updateState(Integer userId, Integer state) {
        if (userId == null) {
            return JsonResult.error("参数userId不能为空");
        }
        if (state == null || (state != 0 && state != 1)) {
            return JsonResult.error("状态值不正确");
        }
        User user = new User();
        user.setUserId(userId);
        user.setState(state);
        if (userService.updateById(user)) {
            return JsonResult.ok();
        } else {
            return JsonResult.error();
        }
    }

    @ResponseBody
    @RequestMapping("/clearLoginLimit")
    @OperLog(module = "SYS", desc = "系统用户列表-清除登录限制", result = true)
    public JsonResult clearLoginLimit(String username) {
        if (StringUtils.isBlank(username)) {
            return JsonResult.error("参数userId不能为空");
        }
        String key = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "-" + username;
        redisService.delete(UserKey.mngUserLock, key);
        return JsonResult.ok();
    }


    /**
     * 删除用户
     **/
    @RequiresPermissions(value = {"user:update", "user:updateByPartB"}, logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/delete")
    @OperLog(module = "SYS", desc = "系统用户列表-删除", result = true)
    public JsonResult delete(Integer userId) {
        if (userId == null) {
            return JsonResult.error("参数userId不能为空");
        }
        if (userService.removeById(userId)) {
            return JsonResult.ok("删除成功");
        } else {
            return JsonResult.error("删除失败");
        }
    }

    /**
     * 重置密码
     **/
    @RequiresPermissions(value = {"user:update", "user:updateByPartB"}, logical = Logical.OR)
    @ResponseBody
    @RequestMapping("/restPsw")
    @OperLog(module = "SYS", desc = "系统用户列表-重置密码", result = true)
    public JsonResult resetPsw(Integer userId) {
        if (userId == null) {
            return JsonResult.error("参数userId不能为空");
        }
        User user = new User();
        user.setUserId(userId);
        user.setPassword(EndecryptUtil.encrytMd5(DEFAULT_PSW, 3));
        if (userService.updateById(user)) {
            return JsonResult.ok("重置成功，初始密码为" + DEFAULT_PSW);
        } else {
            return JsonResult.error("重置失败");
        }
    }

    /**
     * 修改自己密码
     **/
    @ResponseBody
    @RequestMapping("/updatePsw")
    @OperLog(module = "SYS", desc = "系统用户列表-修改密码")
    public JsonResult updatePsw(String oldPsw, String newPsw) {
        if (StringUtils.isAnyBlank(oldPsw, newPsw)) {
            return JsonResult.error("参数不能为空");
        }
        if (oldPsw.equals(newPsw)) {
            return JsonResult.error("新密码不能与旧密码一致");
        }
        if (getLoginUser() == null) {
            return JsonResult.error("未登录");
        }
        if (!RegExpUtil.complexPwd(newPsw)) {
            return JsonResult.error("至少包含数字和字母的6位以上字符");
        }
        if (!getLoginUser().getPassword().equals(EndecryptUtil.encrytMd5(oldPsw, 3))) {
            return JsonResult.error("原密码输入不正确");
        }
        User user = new User();
        user.setUserId(getLoginUser().getUserId());
        user.setPassword(EndecryptUtil.encrytMd5(newPsw, 3));
        if (userService.updateById(user)) {
            return JsonResult.ok("修改成功");
        } else {
            return JsonResult.error("修改失败");
        }
    }
}
